using RaceHFTools.BluetoothLE.Bean;
using RaceHFTools.BluetoothLE.Bean.Module;
using System;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace RaceHFTools.Pages
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class TweakSdcardPage : ContentPage
    {
        private readonly Bean bean;

        public TweakSdcardPage(Bean bean)
        {
            InitializeComponent();

            this.bean = bean;
        }

        #region 事件处理

        void OnSpaceGet(uint total, uint free)
        {
            Device.BeginInvokeOnMainThread(() =>
            {
                if (total >= 4096 * 1024)
                {
                    float ftotal = (float)total / 1024.0f / 1024.0f;
                    float ffree = (float)free / 1024.0f / 1024.0f;
                    lblSize.Text = $"{(ftotal - ffree).ToString("F2")}GB/{ftotal.ToString("F2")}GB";
                }
                else
                {
                    float ftotal = (float)total / 1024.0f;
                    float ffree = (float)free / 1024.0f;
                    lblSize.Text = $"{(ftotal - ffree).ToString("F2")}MB/{ftotal.ToString("F2")}MB";
                }
            });
        }

        void OnFormatSet(bool success)
        {
            Device.BeginInvokeOnMainThread(() =>
            {
                DisplayAlert("格式化SD卡", success ? "成功": "失败", "确认");
            });
        }

        void OnFaliReasonGet(TweakSdcardFailReason reason)
        {
            Device.BeginInvokeOnMainThread(() =>
            {
            });
        }

        async Task<bool> DoFormatSet()
        {
            await bean.Tweak.SetSdcardFormat();

            return true;
        }
        #endregion

        #region OnAppearing/OnDisappearing
        protected override void OnAppearing()
        {
            base.OnAppearing();

            bean.Tweak.SdcardGetSpaceEvent += OnSpaceGet;
            bean.Tweak.SdcardSetFormat += OnFormatSet;
            bean.Tweak.SdcardGetFailEvent += OnFaliReasonGet;

            _ = bean.Tweak.GetSdcardAll();
        }

        protected override void OnDisappearing()
        {
            bean.Tweak.SdcardGetSpaceEvent -= OnSpaceGet;
            bean.Tweak.SdcardSetFormat -= OnFormatSet;
            bean.Tweak.SdcardGetFailEvent -= OnFaliReasonGet;

            base.OnDisappearing();
        }
        #endregion

        #region 交互事件
        async void Button_TweakFormat_Clicked(object sender, EventArgs e)
        {
            await DoFormatSet();
        }
        #endregion
    }
}
